<?php
# @Date:   2017-08-24 14:24:54
# @Email:  tianming2015@foxmail.com
# @Last modified time: 2020-07-28 14:13:00
use HyperDown\Parser;
use Illuminate\Support\Facades\Redis;

if (!function_exists('randCode')) {
    /**
     * 生成随机字符串
     * @param  int       $length  要生成的随机字符串长度
     * @param  string    $type    随机码类型：0，数字+大小写字母；1，数字；2，小写字母；3，大写字母；4，特殊字符；-1，数字+大小写字母+特殊字符；5，数字+小写字母
     * @return string
     * @author  tm
     * @date    2016-08-29
    */
    function randCode($length = 5, $type = 0) {
        $arr = array(1 => "0123456789", 2 => "abcdefghijklmnopqrstuvwxyz", 3 => "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4 => "~@#$%^&*(){}[]|");
        if ($type == 0) {
            array_pop($arr);
            $string = implode("", $arr);
        } elseif ($type == "-1") {
            $string = implode("", $arr);
        } elseif ($type == "5") {
            array_pop($arr);
            array_pop($arr);
            $string = implode("", $arr);
        } else {
            $string = $arr[$type];
        }
        $count = strlen($string) - 1;
        $code = '';
        for ($i = 0; $i < $length; $i++) {
            $code .= $string[rand(0, $count)];
        }
        return $code;
    }
}
if (!function_exists('curl')) {
    /**
     * [curl description]
     * @param  [type]  $url    [description]
     * @param  boolean $params [description]
     * @param  integer $ispost [description]
     * @param  integer $https  [description]
     * @return [type]          [description]
     */
    function curl($url, $params = false, $ispost = 0, $https = 0,$headers=[]) {
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if (!empty($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        if ($https) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
        }
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            if ($params) {
                if (is_array($params)) {
                    $params = http_build_query($params);
                }
                curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
            } else {
                curl_setopt($ch, CURLOPT_URL, $url);
            }
        }

        $response = curl_exec($ch);

        if ($response === FALSE) {
            return false;
        }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
        curl_close($ch);
        return $response;
    }
}

if ( !function_exists('puturl') ) {
    /**
     * [puturl description]
     * @param  [type] $url    [description]
     * @param  [type] $data   [description]
     * @param  string $method [description]
     * @return [type]         [description]
     */
    function puturl($url,$data){
        $data = json_encode($data);
        $ch = curl_init(); //初始化CURL句柄
        curl_setopt($ch, CURLOPT_URL, $url); //设置请求的URL
        curl_setopt ($ch, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //设为TRUE把curl_exec()结果转化为字串，而不是直接输出
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"PUT"); //设置请求方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置提交的字符串
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }
}

if ( !function_exists('deleteurl') ) {
    /**
     * [puturl description]
     * @param  [type] $url    [description]
     * @param  [type] $data   [description]
     * @param  string $method [description]
     * @return [type]         [description]
     */
    function deleteurl($url,$data){
        $data = json_encode($data);
        $ch = curl_init(); //初始化CURL句柄
        curl_setopt($ch, CURLOPT_URL, $url); //设置请求的URL
        curl_setopt ($ch, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //设为TRUE把curl_exec()结果转化为字串，而不是直接输出
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"DELETE"); //设置请求方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置提交的字符串
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }
}

/**
 * 将二维数组的键值转换为子数组的中ID值
 * @param array  $array			待转换的二维数组
 * @return array				键值为数组中ID值的数组
 *
 * @author						tm
 * @date						2016-07-08
 */
if (!function_exists('array_id_key')) {
    function array_id_key($array){
    	$temp_arr = array();
    	foreach($array as $val){
    		$temp_arr[$val['id']] = $val;
    	}
    	$array = $temp_arr;
    	return $array;
    }
}


if (!function_exists('d')) {
	function d($data)
	{
		var_dump($data);
        die();
	}
}

if (!function_exists('timeAgo')) {
    /**
     * 距离现在时间
     * @param  [type] $date [description]
     * @return [type]       [description]
     */
    function timeAgo($date) {
    	$t = time ();
    	$a = $t - strtotime ( $date );
    	$a = date ( 'Y-m-d H:i:s', $a );
    	$b = explode ( ' ', $a );
    	$c = explode ( '-', $b [0] );
    	$d = explode ( ':', $b [1] );
    	if ($c [0] != '1970') {
    		$e = (intval ( $c [0] ) - 1970) . '年前';
    	} else if ($c [1] != '01') {
    		$e = (intval ( $c [1] ) - 1) . '个月前';
    	} else if ($c [2] != '01') {
    		$e = (intval ( $c [2] ) - 1) . '天前';
    	} else if ($d [0] != '08') {
    		$e = (intval ( $d [0] ) - 8) . '小时前';
    	} else if ($d [0] != '00') {
    		$e = (intval ( $d [1] )) . '分钟前';
    	} else {
    		$e = '1分钟内';
    	}
    	return $e;
    }
}

if ( !function_exists('briefTime') ) {
    /*
     * 将常用时间格式(2016-08-11)转化成简单时间格式(15/8/11)
     * @param     string   $time		待处理时间格式

     * @author    tm
     * @date      2017-08-26
     * @return    string
     * */
     function  briefTime($time){
    	return substr(str_replace('-','/',$time),2,8);
     }
}

if (!function_exists('getTheMonth')) {
    /**
     * 获取指定日期所在月的第一天和最后一天
     * @param [type] $date [description]
     */
    function GetTheMonth($date){
        $firstday = date("Y-m-01",strtotime($date));
        $lastday = date("Y-m-d",strtotime("$firstday +1 month -1 day"));
        return array($firstday,$lastday);
    }
}

if ( !function_exists('markdown_to_html') ) {
	/**
	 * 把markdown转为html
	 *
	 * @param $markdown
	 * @return mixed|string
	 */
	function markdown_to_html($markdown)
	{
		// 正则匹配到全部的iframe
		preg_match_all('/&lt;iframe.*iframe&gt;/', $markdown, $iframe);
		// 如果有iframe 则先替换为临时字符串
		if (!empty($iframe[0])) {
			$tmp = [];
			// 组合临时字符串
			foreach ($iframe[0] as $k => $v) {
				$tmp[] = '【iframe'.$k.'】';
			}
			// 替换临时字符串
			$markdown = str_replace($iframe[0], $tmp, $markdown);
			// 讲iframe转义
			$replace = array_map(function ($v){
				return htmlspecialchars_decode($v);
			}, $iframe[0]);
		}
		// markdown转html
		$parser = new Parser();
		$html = $parser->makeHtml($markdown);
		$html = str_replace('<code class="', '<code class="lang-', $html);
		// 将临时字符串替换为iframe
		if (!empty($iframe[0])) {
			$html = str_replace($tmp, $replace, $html);
		}
		return $html;
	}
}

if ( !function_exists('re_substr') ) {
	/**
	 * 字符串截取，支持中文和其他编码
	 *
	 * @param string  $str 需要转换的字符串
	 * @param integer $start 开始位置
	 * @param string  $length 截取长度
	 * @param boolean $suffix 截断显示字符
	 * @param string  $charset 编码格式
	 * @return string
	 */
	function re_substr($str, $start = 0, $length, $suffix = true, $charset = "utf-8") {
		$slice = mb_substr($str, $start, $length, $charset);
		$omit = mb_strlen($str) >= $length ? '...' : '';
		return $suffix ? $slice.$omit : $slice;
	}
}

if ( !function_exists('AddLoginLog') ) {
	/**
	 * [AddLoginLog description]
	 * @param integer $id   [description]
	 * @param [type]  $name [description]
	 * @param string  $time [description]
	 */
	function AddLoginLog($id=0,$name=null,$time='') {
        $redis = Redis::connection();
        $data1 = $redis->RPOP('list');//取出
        var_dump($data1);
        die();
        if (!$data1) d('123');
        $result = unserialize($data1);
        d($data1);
        // $data = array(array('id'=>3,'name'=>'小米1'),array('id'=>4,'name'=>'tom2'));
        // $str = serialize($data);
        // Redis::LPUSH('list',$str);//存入队列
	}
}

//使用array_keys搜索指定的值再循环unset）
if ( !function_exists('delByValue') ) {
    function delByValue($arr, $value){
        $keys = array_keys($arr, $value);
        if(!empty($keys)){
            foreach ($keys as $key) {
                unset($arr[$key]);
            }
        }
        return $arr;
    }
}

if ( !function_exists('addFileToZip') ) {
    function addFileToZip($path) {
        // Get real path for our folder
        // $path = realpath('folder-to-zip');
        // Initialize archive object
        $zip = new ZipArchive();
        $zip->open($path.'file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);

        // Initialize empty "delete list"
        $filesToDelete = array();

        // Create recursive directory iterator
        /** @var SplFileInfo[] $files */
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($path),
            RecursiveIteratorIterator::LEAVES_ONLY
        );

        foreach ($files as $name => $file)
        {
            // Skip directories (they would be added automatically)
            if (!$file->isDir())
            {
                // Get real and relative path for current file
                $filePath = $file->getRealPath();
                $relativePath = substr($filePath, strlen($path) + 1);

                // Add current file to archive
                $zip->addFile($filePath, $relativePath);

                // Add current file to "delete list"
                // delete it later cause ZipArchive create archive only after calling close function and ZipArchive lock files until archive created)
                if ($file->getFilename() != 'file.zip')
                {
                    $filesToDelete[] = $filePath;
                }
            }
        }

        // Zip archive will be created only after closing object
        $zip->close();

        // Delete all files from "delete list"
        foreach ($filesToDelete as $file)
        {
            unlink($file);
        }
    }
}


if ( !function_exists('base64EncodeImage') ) {
    /**
     * 图片转base64
     * @return [type] [description]
     */
    function base64EncodeImage($image_file) {
        $base64_image = '';
        $image_info = getimagesize($image_file);
        $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
        $base64_image = chunk_split(base64_encode($image_data));
        return $base64_image;
    }
}

if ( !function_exists('creatPaginator') ) {
    /**
     * 图片转base64
     * @return [type] [description]
     */
    function creatPaginator($slice, $count, $pageSize, $page) {
        $res = array(
            "current_page" => $page,
            "data" => $slice,
            "last_page" => ceil($count/$pageSize),
            "per_page" => $pageSize,
            "total" => $count
        );
        return $res;
    }
}

if ( !function_exists('is_Date') ) {
    /**
     * 判断日期格式是否正确
     * @param  [type]  $str    [description]
     * @param  string  $format [description]
     * @return boolean         [description]
     */
    function is_Date($str,$format='Y-m-d'){
        $unixTime_1=strtotime($str);
        if(!is_numeric($unixTime_1)) return false; //如果不是数字格式，则直接返回
        $checkDate=date($format,$unixTime_1);
        $unixTime_2=strtotime($checkDate);
        if($unixTime_1==$unixTime_2){
            return true;
        }else{
            return false;
        }
    }
}
